import React, { useState, useEffect } from 'react';
import axios from 'axios';
import { Button, Dialog, DialogTitle, DialogContent } from '@mui/material';
import "./styles/Reports.css"


const ChangeReport = ({ open, setOpenChangeDialog, report, m}) => {
    const [file, setFile] = useState(null);
    const [title, setTitle] = useState('');
    useEffect(() => {
        if(report !== null){
            setTitle(report.action)
        }
        else{
            setTitle(m)
        }
        
    }, [report, m])


    const addReport = async () => {
        try {
            const headers = {
                'Authorization': `Bearer ${localStorage.getItem('accessToken')}`,
                'Content-Type': 'multipart/form-data'
            };
            const newReport = new FormData()
            //newReport.append("id", id)
            newReport.append("title", title)
            newReport.append("file", file)
            const response = await axios.put('http://localhost:8000/api/report', newReport, { headers });
            console.log('New report added:', response.data);
            setOpenChangeDialog(false);
        } catch (error) {
            console.error('Error adding new report:', error);
        }
    };

    const downloadReport = () => {
        const downloadLink = document.createElement('a');
        downloadLink.href = report.file;
        downloadLink.download = report.file.split('/').pop(); // Получаем имя файла из URL
        document.body.appendChild(downloadLink);
        downloadLink.click();
        document.body.removeChild(downloadLink);
      };

    const handleTitle = (event) => {
        setTitle(event.target.value);
    };
    const handleCloseDialog = () => {
        setOpenChangeDialog(false);
    };


    return (
        <Dialog
            sx={{ '& .MuiDialog-paper': { width: '80%', maxWidth: 'none', backgroundColor: "black", boxShadow: '0 0 30px 5px rgb(13, 127, 0)'} }}
            open={open}
            onClose={handleCloseDialog}
        >
            <DialogTitle><label fontWeight={'black'} style={{ color: 'white' }}>Добавить новые данные</label></DialogTitle>
            <DialogContent>
                <div>
                    <div className='input-table-container'>
                        <div style={{ display: 'flex', flexDirection: "column", gap: '20px', alignItems: 'center' }}>
                            <label>Заполните содержание отчета</label>
                            <textarea className='input-form-table'
                                value={title}
                                onChange={handleTitle}
                                style={{ borderColor: '#017f10', margin: 0 }}
                            />
                            <Button onClick={report == null? addReport: downloadReport} sx={{ margin: 3, width: '50%', color: 'white', borderRadius: '15px', backgroundColor: '#017f10', '&:focus': { backgroundColor: '#d04b4b' }, '&:hover': { backgroundColor: '#d04b4b' }, fontStyle: { fontColor: 'white', fontSize: 20, fontWeight: 'bolder', fontFamily: "Montserrat" } }} variant={'contained'}>
                                {report == null? "Сохранить": "Скачать"}
                            </Button>
                        </div>
                    </div>

                </div>
            </DialogContent>
        </Dialog>
    );
};

export default ChangeReport;

